package com.xnf.comment.filter;

import com.xnf.model.user.pojos.ApUser;
import com.xnf.utils.AppThreadLocalUtils;
import com.xnf.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xnf on 2022/3/14.
 */
@Order(1)
@WebFilter(urlPatterns = "/*",filterName = "appTokenFilter")
public class AppTokenFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String token = request.getHeader("token");
        if (token != null ){
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (claims != null && claims.get("id") != null){
                Integer userId = (Integer) claims.get("id");
                ApUser apUser = new ApUser();
                apUser.setId(userId);
                AppThreadLocalUtils.set(apUser);
            }
        }

        chain.doFilter(req,res);
    }


}